const assert = require("assert");
var jwt = require("jsonwebtoken");
module.exports = class extends think.Controller {
  static get _REST() {
    return true;
  }

  constructor(ctx) {
    super(ctx);
    this.resource = this.getResource();
    this.id = this.getId();

    assert(think.isFunction(this.model), "this.model must be a function");
    this.modelInstance = this.model(this.resource);
  }
  async __before() {
    let tokensd = await this.analysisToken(this.ctx.header.token);
    if (!tokensd) {
      if (this.ctx.url == "/dxgjAdmin/menumg") {
        return this.fail({
          errno: -2,
          errmsg: "token已过期请重新登录",
        });
      } else {
        return this.fail({
          errno: -2,
          errmsg: "token已过期请重新登录",
        });
      }
    }
  }
  /**
   * get resource
   * @return {String} [resource name]
   */
  getResource() {
    return this.ctx.controller.split("/").pop();
  }
  getId() {
    const id = this.get("id");
    if (id && (think.isString(id) || think.isNumber(id))) {
      return id;
    }
    const last = this.ctx.path.split("/").slice(-1)[0];
    if (last !== this.resource) {
      return last;
    }
    return "";
  }
  async getAction() {
    let data;
    let cg = this.get();
    if (this.id) {
      const pk = this.modelInstance.pk;
      data = await this.modelInstance
        .where({
          [pk]: this.id,
        })
        .find();
      return this.success(data);
    }
    if (cg.page) {
      let obj = {};
      for (let key in cg) {
        if (key != "page"&& key != "pageSize") {
          let jhse = cg[key].split(",");
          let jhbser = [];
          jhse.map((a) => {
            if (key == "state") {
              jhbser.push(a);
            } else {
              jhbser.push(`%${a}%`);
            }
          });
          console.log(jhbser);
          obj[key] = ["like", jhbser];
        }
      }

      data = await this.modelInstance
        .where(obj)
        .page(cg.page, parseInt(cg.pageSize) || 10)
        .order("id DESC")
        .countSelect();
      return this.success(data);
    }
    if (cg) {
      let obj = {};
      for (let key in cg) {
        if (key != "page") {
          let jhse = cg[key].split(",");
          let jhbser = [];
          jhse.map((a) => {
            jhbser.push(`%${a}%`);
          });
          console.log(jhbser);
          obj[key] = ["like", jhbser];
        }
      }
      if (this.ctx.url == "/dxgjAdmin/menumg") {
        data = await this.modelInstance
          .where(obj)
          .order("menuIindex ASC")
          .select();
        let objs = {};
        objs.data = data; //存入token的数据
        objs.ctime = new Date().getTime(); //token的创建时间
        objs.expiresIn = 1000 * 60 * 60 * 2; //设定的过期时间
        /**1111111
                data = jwt.sign(objs, this.config('secretKeytoken'));
                */
        /*加密处理*/
      } else {
        data = await this.modelInstance.where(obj).order("id ASC").select();
      }

      return this.success(data);
    }
    data = await this.modelInstance.select();
    return this.success(data);
  }
  /**
   * put resource
   * @return {Promise} []
   */
  async postAction() {
    const pk = this.modelInstance.pk;
    const data = this.post();
    delete data[pk];
    if (think.isEmpty(data)) {
      return this.fail("data is empty");
    }
   try{
    const number = await this.modelInstance.max("paixu");
    data.paixu = number + 1;
   }catch(e){
    
   }
    
    let insertId = "";
    let msgText = "添加成功",
      code = 0;
    data.addTime = this.timeCycle(new Date().getTime());
    if (data.dateManufacture) {
      data.dateManufacture = this.timeCycle(data.dateManufacture);
    }
    if (data.thenAdd) {
      let duix = {};
      duix[data.thenAdd] = data[data.thenAdd];
      insertId = await this.modelInstance.thenAdd(data, duix);
      if (insertId.type == "exist") {
        msgText = "有重复的数据";
        code = -1;
      }
    } else {
      insertId = await this.modelInstance.add(data);
    }

    if (code == -1) {
      return this.fail(code, msgText);
    } else {
      return this.success({
        msg: msgText,
        insertId,
      });
    }
  }
  /**
   * delete resource
   * @return {Promise} []
   */
  async deleteAction() {
    if (!this.id) {
      return this.fail("params error");
    }
    const idsList = this.get("id").split(",");
    let cs = this.id;
    if (idsList.length > 0) {
      cs = idsList;
    }
    const pk = this.modelInstance.pk;
    const rows = await this.modelInstance
      .where({
        [pk]: cs,
      })
      .delete();
    return this.success({
      affectedRows: rows,
    });
  }
  /**
   * update resource
   * @return {Promise} []
   */
  async putAction() {
    const pk = this.modelInstance.pk;
    const data = this.post();
    data.addTime = this.timeCycle(new Date().getTime());
    if (data.dateManufacture) {
      data.dateManufacture = this.timeCycle(data.dateManufacture);
    }
    data[pk] = this.post("id"); // rewrite data[pk] forbidden data[pk] !== this.id
    if (think.isEmpty(data)) {
      return this.fail("data is empty");
    }
    const rows = await this.modelInstance
      .where({
        [pk]: this.post("id"),
      })
      .update(data);
    return this.success({
      affectedRows: rows,
    });
  }
  /**
   * @param t格式化的时间戳
   * @return 2021-12-12 12:12:12 如果t没传返回当前的时间
   **/
  timeCycle(t) {
    let time = new Date();
    if (t) {
      time = new Date(t);
    }
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
      hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
      Minutes =
        time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
      Seconds =
        time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
    Month < 10 ? (Month = 0 + "" + Month) : "";
    return `${Year}-${Month}-${Data} ${hour}:${Minutes}:${Seconds}`;
  }
  analysisToken(token) {
    return new Promise((resolve, reject) => {
      let result = null;
      try {
        let { data, ctime, expiresIn } = jwt.verify(
          token,
          this.config("secretKeytoken")
        );
        let nowTime = new Date().getTime();
        if (nowTime - ctime < expiresIn) {
          result = data;
        }
      } catch (error) {}
      if (result) {
        resolve(result);
      } else {
        resolve("");
      }
    });
  }

  __call() {}
};
